<template>
  <el-upload
    :file-list="fileList"
    :http-request="httpRequest"
    :limit="limit"
    list-type="picture-card"
  >
    <el-icon class="avatar-uploader-icon">
      <Plus />
    </el-icon>
  </el-upload>
</template>
<script lang="ts" setup>
import { ref, watch } from "vue";
import { UploadRequestOptions, UploadUserFile } from "element-plus";
import { Plus } from "@element-plus/icons-vue";
import { uploadMealPicture } from "@/api/meal";
import { convertFileToBase64WithoutMIME ,compressImageToBase64} from "@/utils/file";

const imageUrl = defineModel<string | undefined>();
const fileList = ref<UploadUserFile[]>([]);
const limit = 1;

watch(imageUrl, (newValue) => {
  if (fileList.value.length == 0) {
    fileList.value.push({ url: newValue, name: "" });
  } else if (newValue === undefined) {
    fileList.value = [];
  }
});

async function httpRequest(options: UploadRequestOptions) {
  try {
    // const pictureBase64 = await convertFileToBase64WithoutMIME(options.file);
    const YaSuopictureBase64 = await compressImageToBase64(options.file);

    // console.log(pictureBase64);
    // console.log(YaSuopictureBase64);

    const pictureBase64Data = String(YaSuopictureBase64).split(",")[1];

    const { result } = await uploadMealPicture(pictureBase64Data, options.file.name);
    if (result !== undefined) {
      fileList.value.push({
        name: options.file.name,
        url: result,
      });
      imageUrl.value = result;
    }
  } catch (error) {
    console.error(error);
  }
}


</script>
